package ch.ethz.fcl.metrobuzz.algorithm.voronoi.Paul;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.lwjgl.opengl.GL11;

import ch.ethz.fcl.metrobuzz.spatialindex.object2d.Point2D;
import ch.ethz.fcl.metrobuzz.tools.MBGL;

public class VoronoiDiagram {
	private Triangulation dt; // Delaunay triangulation
	private Triangle initialTriangle; // Initial triangle
	private static float initialSize = 1f; // initial triangle

	private List<Pnt[]> verticesList = null; // record voronoi diagram vertices

	public VoronoiDiagram() {
		initialTriangle = new Triangle(new Pnt(-initialSize, -initialSize),
				new Pnt(initialSize, -initialSize), new Pnt(0, initialSize));
		dt = new Triangulation(initialTriangle);

		verticesList = new ArrayList<Pnt[]>();
	}

	public void addPoint(Point2D p) {
		dt.delaunayPlace(new Pnt(p.getX(), p.getY()));
	}

	public void init() {
		HashSet<Pnt> done = new HashSet<Pnt>(initialTriangle);
		for (Triangle triangle : dt)
			for (Pnt site : triangle) {
				if (done.contains(site))
					continue;
				done.add(site);
				List<Triangle> list = dt.surroundingTriangles(site, triangle);
				Pnt[] vertices = new Pnt[list.size()];
				int i = 0;
				for (Triangle tri : list)
					vertices[i++] = tri.getCircumcenter();

				verticesList.add(vertices);
			}
	}

	public void render() {
		MBGL.enableBlend();

		GL11.glLineWidth(1.0f);

		for (Pnt[] vertices : verticesList) {
			GL11.glColor4f(0, 0, 1, 1);
			GL11.glBegin(GL11.GL_LINE_STRIP);
			for (Pnt vertex : vertices)
				GL11.glVertex2d(vertex.coord(0), vertex.coord(1));

			GL11.glVertex2d(vertices[0].coord(0), vertices[0].coord(1));
			GL11.glEnd();
		}

		GL11.glColor4f(1, 0, 0, 1);
		GL11.glPointSize(5);
		GL11.glBegin(GL11.GL_POINTS);
		for (Triangle triangle : dt)
			for (Pnt site : triangle) {
				GL11.glVertex2d(site.coord(0), site.coord(1));
			}

		GL11.glEnd();
		MBGL.disableBlend();
	}
}
